package com.epam.web_project.bank.command;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.epam.web_project.bank.dao.customer_dao.CustomerDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Customer;
import com.epam.web_project.bank.exception.WrongPasswordException;
import com.epam.web_project.bank.util.AppPropertiesLoader;
import com.epam.web_project.bank.util.PasswordEncoder;

public class LoginCommand implements Command {
	 private static Logger logger=Logger.getLogger(LoginCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String pass = request.getParameter("password");
		String passHash = PasswordEncoder.sha2Encode(pass);
		String resPage = "";
		HttpSession session = request.getSession(true);
		MySQLDAOFactory daoFactory = new MySQLDAOFactory();
		daoFactory.setConnectionPool(ConnectionPool.getInstance());
		CustomerDAO customerDAO = daoFactory.getCustomerDAO();
		Customer customer = customerDAO.userAuth(login, passHash);
		AppPropertiesLoader propLoader = AppPropertiesLoader.getInstance();
		if (customer != null && !customer.isDeleted()) {
			if (!customer.isOnApproval()) {
				if ("customer".equals(customer.getRole())) { // customer
					session.setAttribute("customer", customer);
					resPage = propLoader.getProperty("show_main_command");
				} else if ("admin".equals(customer.getRole())) { // admin
					session.setAttribute("customer", customer);
					resPage = propLoader.getProperty("show_admin_main_command");
				}
			} else { // new unapproved customer
				session.setAttribute("customer", customer);
				resPage = propLoader.getProperty("show_unnaproved_command");
			}
		} else { // deleted user or wrong login/password
			session.invalidate();
			throw new WrongPasswordException("Login / password is wrong!");
		}
		return resPage;
	}

}
